package com.jcf.springboot.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

  @Bean
  public Docket webApiConfig() {
    return new Docket(DocumentationType.SWAGGER_2)
     .groupName("webApi")
     .apiInfo(webApiInfo())
     .select()
     .apis(RequestHandlerSelectors.basePackage("com.jcf.springboot.controller"))
     .paths(PathSelectors.any())
     .build()
     .securityContexts(securityContexts())
     .securitySchemes(securitySchemes());


  }

  private ApiInfo webApiInfo() {

    return new ApiInfoBuilder()
     .title("网站-梓晨影院API文档")
     .description("本文档描述了梓晨影院接口定义")
     .version("2.0")
     .contact(new Contact("java", "http://jcf.com", "1822240581@qq.com"))
     .build();
  }
  public List<ApiKey> securitySchemes(){
    List<ApiKey> result = new ArrayList<>();
    ApiKey apiKey = new ApiKey("token","token","Header");
    result.add(apiKey);
    return result;
  }

  private  List<SecurityContext> securityContexts(){
    List<SecurityContext> result = new ArrayList<>();
    result.add(getContextByPath("/common/.*"));
    return  result;
  }

  private SecurityContext getContextByPath(String pathRegex){
    return SecurityContext.builder()
     .securityReferences(defaultAuth())
     .forPaths((PathSelectors.regex(pathRegex)))
     .build();

  }

  private List<SecurityReference> defaultAuth(){
    List<SecurityReference> result = new ArrayList<>();
    AuthorizationScope authorizationScope = new AuthorizationScope("global","accessEverythingt");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    result.add(new SecurityReference("token",authorizationScopes));
    return result;
  }

}
